import { createBrowserRouter, RouterProvider } from "react-router-dom";
import MainLayout from "@/Layout/MainLayout";
import Login from "@/pages/Login/index";
import NotFound from "@/pages/NotFound/index";
import React from "react";
import useAuthStore from "@/store/authStore";
import { Spin } from "antd";

const modules = import.meta.glob("@/pages/**/*.jsx");

// 处理嵌套路由
const generateRoutes = (menus) => {
  return menus.map((menu) => {
    const route = {
      path: menu.path,
      meta: menu.meta,
    };

    if (menu.component) {
      const Component = React.lazy(modules[`/src/pages/${menu.component}.jsx`]);
      route.element = (
        <React.Suspense
          fallback={
            <div className="flex items-center justify-center h-full">
              <Spin />
            </div>
          }
        >
          <Component />
        </React.Suspense>
      );
    }

    if (menu.children) {
      route.children = generateRoutes(menu.children);
    }

    if (menu.redirect) {
      route.redirect = menu.redirect;
    }
    return route;
  });
};

export default function AppRouter() {
  const { menus } = useAuthStore(); // ✅ Hook 在组件里调用
  const dynamicChildren = generateRoutes(menus?.length ? menus : []);

  const router = createBrowserRouter([
    {
      path: "/",
      element: <MainLayout />,
      children: dynamicChildren,
    },
    {
      path: "/login",
      element: <Login />,
    },
    {
      path: "*",
      element: <NotFound />,
    },
  ]);

  return <RouterProvider router={router} />;
}
